<template>
  <el-upload
    class="upload-demo"
    drag
    action="#"
    accept=".xlsx,.xls"
    multiple
    :limit="1"
    :auto-upload="false"
    :on-change="onChangeFile"
  >
    <el-icon class="el-icon--upload">
      <upload-filled />
    </el-icon>
    <div class="el-upload__text">
      {{ `${$t('upload.tip')}, ${$t('common.or')}` }}
      <em>{{ $t('upload.click_upload') }}</em>
    </div>
    <template #tip v-if="$slots.tip">
      <div class="el-upload__tip">
        <slot name="tip"></slot>
      </div>
    </template>
  </el-upload>
</template>

<script setup lang="ts" name="T_Upload">
import { UploadFilled } from '@element-plus/icons-vue'
import { UploadProps } from 'element-plus'
const handleMsg = (str: string) => {
  ElMessage({
    showClose: true,
    message: str,
    type: 'info'
  })
}
const onChangeFile: UploadProps['onChange'] = (file, files) => {
  if (file.status === 'ready') {
    let myFile = file.raw
    const fileIndex = files.findIndex(item => item.name === file.name && item.uid !== file.uid)
    if (fileIndex >= 0) {
      files[fileIndex] = file
      files.pop()
      handleMsg(`${myFile?.name}重复，已替换`)
    }
  }
  if (file.status === 'fail') {
    ElMessage({
      showClose: true,
      message: '文件上传失败',
      type: 'error'
    })
  }
}
</script>

<style lang="scss" scoped>
.upload-demo {
  padding: 0 20px;
}
.el-upload__tip {
  margin-top: 14px;
  font-size: 14px;
}
</style>
